package components

import (
	"encoding/json"
	"fmt"
	"fyne.io/fyne"
	"fyne.io/fyne/container"
	"fyne.io/fyne/dialog"
	"fyne.io/fyne/widget"
	"io/ioutil"
	"strconv"
	"totest/src/pojo"
)

var sourceFile = pojo.SOURCE_FILE

func NewWindowOfCenter(title string, size fyne.Size, can ...fyne.CanvasObject) fyne.Window {
	w := fyne.CurrentApp().NewWindow(title)
	w.Resize(size)
	w.SetContent(
		container.NewVBox(
			can...,
		))
	w.CenterOnScreen()
	w.Show()
	return w
}

func NewWindowOfCenterNoconent(title string, size fyne.Size) fyne.Window {
	w := fyne.CurrentApp().NewWindow(title)
	w.Resize(size)
	w.CenterOnScreen()
	return w
}

/**
用来创建一个指定了大小的窗口
用于数据展示
*/
func NewWindowOfFixedAndCenter(title string, can ...fyne.CanvasObject) {
	NewWindowOfCenter(title, fyne.Size{
		Width:  350,
		Height: 400,
	}, can...)
}

/**
创建一个表单
*/
func MakeFormTab(source *pojo.DataSource, w fyne.Window) (fyne.CanvasObject, *pojo.DataSource) {
	userName, password, dbName, ip, port, dbType := widget.NewEntry(), widget.NewEntry(), widget.NewEntry(), widget.NewEntry(), widget.NewEntry(), widget.NewEntry()
	userName.SetPlaceHolder("数据库用户名")
	password.SetPlaceHolder("数据库密码")
	dbName.SetPlaceHolder("数据库名称")
	ip.SetPlaceHolder("数据库ip")
	port.SetPlaceHolder("数据库端口号")
	dbType.SetPlaceHolder("数据库类型 oracle/mysql")
	jb, ok := ioutil.ReadFile(sourceFile)
	sou := new(pojo.DataSource)
	if ok == nil {
		if len(jb) > 5 {
			jsonOK := json.Unmarshal(jb, sou)
			if jsonOK == nil {
				userName.SetText(sou.UserName)
				password.SetText(sou.Password)
				dbName.SetText(sou.DbName)
				ip.SetText(sou.Ip)
				port.SetText(strconv.Itoa(sou.Port))
				dbType.SetText(sou.DbType)
			} else {
				fmt.Println(jsonOK)
			}
		}
	}

	form := &widget.Form{
		Items: []*widget.FormItem{
			{Text: "数据库用户名", Widget: userName},
			{Text: "数据库密码", Widget: password},
			{Text: "数据库名称", Widget: dbName},
			{Text: "数据库ip", Widget: ip},
			{Text: "数据库端口号", Widget: port},
			{Text: "数据库类型", Widget: dbType},
		},
		OnSubmit: func() {
			_port, _ := strconv.Atoi(port.Text)
			source.UserName,
				source.Password,
				source.DbName,
				source.Ip,
				source.Port,
				source.Extend,
				source.DbType = userName.Text,
				password.Text,
				dbName.Text,
				ip.Text,
				_port,
				"",
				dbType.Text
			switch dbType.Text {
			case "oracle":
				source.Method = new(pojo.OracleSource)
			case "mysql":
				source.Method = new(pojo.MysqlSource)
			default:
				source.Method = new(pojo.OracleSource)
			}
			_, _, str := source.CreateLink()
			fmt.Printf("%v%p\n", "form", source)
			if str == "" {
				dialog.ShowInformation("连接提示", "连接失败", w)
			} else {
				by, _ := json.Marshal(source)
				ioutil.WriteFile(sourceFile, by, 0666)
				dialog.ShowInformation("连接提示", str, w)
			}
		},
	}
	return form, source
}
